/**
 * Created by joy on 03/09/2017.
 */

import CommonUtil from '../../common/utils/CommonUtil'
import prompt from 'prompt'
import BitcoinRpcHelper from '../../common/helpers/chain/BitcoinRpcHelper'
import lineReader from 'line-reader'

export default () => {
  return new Promise(async (resolve, reject) => {
    try {
      const schema = {
        properties: {
          host: {
            description: 'Enter host of node',
            type: 'string',
            required: true,
            default: '127.0.0.1'
          },
          port: {
            description: 'Enter port of node',
            type: 'number',
            required: true,
            default: 18332
          },
          user: {
            description: 'Enter rpc user of node',
            type: 'string',
            required: true,
            default: 'test'
          },
          password: {
            description: 'Enter rpc password of node',
            type: 'string',
            hidden: true,
            replace: '*',
            required: true,
            default: '123456789'
          },
          input: {
            description: 'Enter unsigned filename',
            type: 'string',
            required: true,
            default: 'temp_data/signed.txt'
          }
        }
      }

      const args = await CommonUtil.getArgsFromConsole(prompt, schema)
      const { host, port, user, password, input } = args
      const bitcoinRpcHelper = new BitcoinRpcHelper(host, port, user, password)
      lineReader.eachLine(input, async (line, last) => {
        const { txHex, txId } = JSON.parse(line)
        try {
          await bitcoinRpcHelper.sendRawTransaction(txHex)
          logger.info(`txId: ${txId} 广播成功`)
        } catch (err) {
          logger.error(`txId: ${txId} 广播失败`)
          logger.error(err)
          // reject(err)
        }
      })
    } catch (err) {
      logger.error(err)
      reject(err)
    }
  })

}
